package polimi.sc.expoquest.storage.datasources;



import polimi.sc.expoquest.storage.DBContract;
import polimi.sc.expoquest.storage.DBHelper;
import polimi.sc.expoquest.storage.model.User;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * This class is in charge of managing all the database
 * operations related to the USER TABLE, using the 
 * database helper, which does the direct calls to the 
 * database
 * SHOULD BE ONE FOR EACH AVAILABLE TABLE IN THE DATABASE 
 * @author Monica Lozano
 *
 */
public class UserDataSource {
	//------------------
	//ATTRIBUTES
	//------------------
	/**
	 * The object that represents the database
	 */
	private SQLiteDatabase db;
	/**
	 * The database helper for accessing the database 
	 */
	private DBHelper dbHelper;
	
	//----------------
	// CONSTRUCTOR
	//----------------
	public UserDataSource(Context ctx)
	{
		//1. We create the DB helper
		dbHelper = new DBHelper(ctx);
	}
	
	//------------------
	//METHODS
	//------------------
	//utilities
	
	/**
	 * Creates the user object from the data in the current
	 * row of the cursor.
	 * @param cursor
	 * @return
	 */
	private User cursorToUser(Cursor cursor)
	{
		User user = new User();
		//1. We obtain the columns indexes based on their names
		int idColIndex = cursor.getColumnIndex(DBContract.User._ID);
		int usernColIndex = cursor.getColumnIndex(DBContract.User.CLM_NAME_USERNAME);
		int passwColIndex = cursor.getColumnIndex(DBContract.User.CLM_NAME_PASSWORD);
		int tsColIndex =cursor.getColumnIndex(DBContract.User.CLM_NAME_TOTALSCORE);
		//2.We obtain the data from the row based on the index
		int id =  cursor.getInt(idColIndex);
		String username = cursor.getString(usernColIndex);
		String password = cursor.getString(passwColIndex);
		int totalScore = cursor.getInt(tsColIndex);
		//3.We save the data in the object
		user.setId(id);
		user.setUsername(username);
		user.setPassword(password);
		user.setTotalScore(totalScore);
		return user;
	}
	
	
	//database connection
	/**
	 * Opens the database such that we can used it for reading and writing
	 */
	public void open(){
		/* 
		 * TODO put this call in a asynchronous task, such that if it takes more than
		 * few seconds our application wont colapse.
		 */
		dbHelper.open();
		db = dbHelper.getWritableDatabase();
	}
	/**
	 * Close the database connection
	 */
	public void close()
	{
		dbHelper.close();
	}
	
	//Database operations
	public User getUserByUsername(String username)
	{
		//3. We return the alarm object saved succesfully into the database
		Cursor cursor = db.query(DBContract.User.TABLE_NAME, 
								DBContract.User.ALL_COLUMNS, 
								DBContract.User.CLM_NAME_USERNAME+ "= ?", 
								new String[]{username}, null, null, null);
		//3.1. Move the cursor to recent inserted row
		boolean nonEmpty=cursor.moveToFirst();
		//3.2. Creating the user object
		if(nonEmpty)
		{
			User user = cursorToUser(cursor);
			//3.3 Closing the cursor
			cursor.close();
			return user;
		}
		return null;
	}
	
	
	/**
	 * @param userID the user id that we are looking for
	 * @return Returns the information of the user that has the userID provided
	 */
	public User getUser(long userID)
	{
		
		//3. We return the alarm object saved succesfully into the database
		Cursor cursor = db.query(DBContract.User.TABLE_NAME, 
								DBContract.User.ALL_COLUMNS, 
								DBContract.User._ID+ "="+ userID, 
								null, null, null, null);
		//3.1. Move the cursor to recent inserted row
		cursor.moveToFirst();
		//3.2. Creating the user object
		User user = cursorToUser(cursor);
		//3.3 Closing the cursor
		cursor.close();
		return user;
	}
	
	/**
	 * Inserts an user
	 * @param username
	 * @param password
	 * @return
	 */
	public User insert(String username, String password)
	{
		//1.We create the values for saving them into the database
		ContentValues values = generateValues(username, password);
		//2. We save it on the database
		long insertID= db.insert(DBContract.User.TABLE_NAME, null, values);
		//3.We retrieve the user just created
		User u = getUser(insertID);
		return u;
	}
	/**
	 * Create the values for query
	 * @param username
	 * @param password
	 * @return
	 */
	private ContentValues generateValues(String username, String password)
	{
		ContentValues values = new ContentValues();
		values.put(DBContract.User.CLM_NAME_USERNAME, username);
		values.put(DBContract.User.CLM_NAME_PASSWORD, password);
		return values;
	}
	/**
	 * Deletes an user
	 * @param user: must containg AT LEAST the user id in the database
	 * @return
	 */
	public boolean delete(User user)
	{
		long id = user.getId();
		int total= db.delete(DBContract.User.TABLE_NAME,
				  DBContract.User._ID+"="+id, null);
		return total>0;
	}
}
